/*********************************************************************************
 * Software License Agreement (BSD License)
 * Copyright (c) 2012, Carlos D. Correa (info@ngraph.org)
 * All rights reserved.
 * 
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 * 
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 * 3. Neither the name of netzen nor the
 *    names of its contributors may be used to endorse or promote products
 *    derived from this software without specific prior written permission.
 * 
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY
 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 *  LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *********************************************************************************/
#include <QImage>
#include <QColor>

#include "glheaders.h"

#include <assert.h>
#include <string.h>
#include <math.h>
#include "renderUtils.h"
#include "mouseUtils.h"
#include "graph.h"
#include "viewcreators.h"
#include "ui/uiUtils.h"
#include "controller.h"
#include <sstream>


/*****************************
MatrixView
*****************************/

class MatrixView: public View {
  float mousex, mousey;
	int numVertices;
	float *vertices;
	float *colors;
	PropertyBag *hoveredNode;
	string curSizeProperty;
	bool invalidateGeometry;
	bool invalidateColors;
 public:
  MatrixView(const char *title): View("MatrixView", title) {
		numVertices = 0; 
		vertices = 0;
		colors = 0;
		hoveredNode = 0;
	  setPropertyStringList("Data.Color", Controller::addVirtualPrefix("edge.color"), "edge");
	  setPropertyStringList("Data.Opacity", "Default", "edge");
		setPropertyStringList("Data.Size", "Default", "edge");
	  setPropertyStringList("Data.Label", "Default", "node");
	  setPropertyStringList("Data.Colormap", Controller::addVirtualPrefix("edge.colormap"), "colormap");
	  setMargins(120, 40, 40, 80);
		curSizeProperty = "";
    invalidateGeometry = true;
    invalidateColors = true;
  }
	void createArrays(int n) {
    if(n!=numVertices || !vertices) {
			this->numVertices = n;
			
			if(vertices) delete vertices;
			vertices = new float[4 * 2 *n];
			
			if(colors) delete colors;        
			colors = new float[4 * 4 * n];
			
    }
	}
	virtual unsigned int numElements() {
		unsigned int k = 0;
		ElementIterator *it = createIterator();
		assert(it);
		for(it->begin();it->hasMoreElements();) {
			it->next();
			k++;
		}
		graph->destroyIterator(it);
		return k;
	}
	virtual ElementIterator * createIterator() {
		return graph->createEdgeIterator();
	}
	
	void updateGeometry() {
    string sizeProperty = PROPERTY(getPropertyString("Data.Size"));
		if(!vertices) return;
    int k = 0;
		float dx0, dy0;
		int n = graph->numNodes();
		int numEdges = numElements();
		dx0 = dy0 = 0.5/((float) n );
		
    ElementIterator *it = createIterator();
    for(it->begin();it->hasMoreElements();) {
			PropertyBag *element = it->next();
			Edge * e = (Edge*) element;
			int id0 = e->getNode0()->getIndex();
			int id1 = e->getNode1()->getIndex();
			float x = (float) id0/(float) n + dx0;
			float y = (float) (n - 1 - id1)/(float) n + dy0;
			assert(8*k+7<8*numEdges);
			
			float size = graph->getAsFloat(element, sizeProperty);
			float dx = dx0 * size;
			float dy = dy0 * size;
			vertices[8*k+0] = x - 1.0*dx;
			vertices[8*k+1] = y - 1.0*dy;
			
			vertices[8*k+2] = x + 1.0*dx;
			vertices[8*k+3] = y - 1.0*dy;
			
			vertices[8*k+4] = x + 1.0*dx;
			vertices[8*k+5] = y + 1.0*dy;
			
			vertices[8*k+6] = x - 1.0*dx;
			vertices[8*k+7] = y + 1.0*dy;
			k++;
    }
    graph->destroyIterator(it);
	}
	
	void updateColors() {
		if(!colors) return;
		string cmap = PROPERTY(getPropertyString("Data.Colormap"));
    string colorProperty = PROPERTY(getPropertyString("Data.Color"));
    string opacityProperty  = PROPERTY(getPropertyString("Data.Opacity"));
    hoveredNode = 0; //reset hover node
    float rgb[3];
    int k = 0;
		bool changedSelection = false;
    ElementIterator *it = createIterator();
		vector<PropertyBag*> selection;
		vector<PropertyBag*> unselection;
    for(it->begin();it->hasMoreElements();) {
			PropertyBag *element = it->next();
			assert(element);
			rgb[0] = rgb[1] = rgb[2] = fColor_front;//0.0;
			
			if(cmap!="Default" && colorProperty!="Default"){
				getAsColor(element, colorProperty, cmap, rgb);
			}
			
			float transparency = graph->getAsFloat(element, opacityProperty);
			float x, y;
			x = 0.5*(vertices[8*k+0] + vertices[8*k+2]);
			y = 0.5*(vertices[8*k+1] + vertices[8*k+5]);
			
			int selected = element->getPropertyInt("node.selected");
			if(dragMode==DRAG) {
				if(inSelection(x, y)) {
					selection.push_back(element);
				} else {
					if(selected==selectionMarker) {
						unselection.push_back(element);
					}
				}
			}
			if(selected>0) {
				getSelectionColor(selected, rgb);
			}
			float px = xpixels(1.0);
			float py = ypixels(1.0);
			float distx = x - mousex;
			float disty = y - mousey;
			float scale  = 1.0;
			if(distx*distx + disty*disty < 2.0*scale*(px*px + py*py)) {
				getSelectionColor(selectionMarker, rgb);
				transparency = 1.8;
				hoveredNode = element; //update hover node
			}
			
			for(int v = 0; v<4;v++) {
				int idx = (4*k + v);
				colors[4*idx+0] = rgb[0];
				colors[4*idx+1] = rgb[1];
				colors[4*idx+2] = rgb[2];
				colors[4*idx+3] = transparency;
			}
			k++;
    }
    graph->destroyIterator(it);
		selectElements(unselection, 0);
		selectElements(selection, selectionMarker);
	
	}

  void render() {
	  string labelProp = PROPERTY(getPropertyString("Data.Label"));
	  
    int N = numElements();
    createArrays(N);
    assert(vertices);
		assert(colors);
		
    if(invalidateGeometry) {
			updateGeometry();
		}
    if(invalidateColors) {
			updateColors();
		}
	  
		float dx = 1.0/((float) graph->numNodes());
		// Geometry
		glColorPointer(4, GL_FLOAT, 0, colors);
		glVertexPointer(2, GL_FLOAT, 0, vertices);
		glEnableClientState(GL_VERTEX_ARRAY);
		glEnableClientState(GL_COLOR_ARRAY);
		glDrawArrays(GL_QUADS, 0, numVertices*4);
		 
	  
		// Labels	  
		glColor4f(0,0,0,1.0);
	  ElementIterator *it = graph->createNodeIterator();

		float maxh = 0;
		int skip = 10;
		int i = 0;
		float lastx = 0;
		float textheight = 0;
	  for(it->begin();it->hasMoreElements();) {	
		  float x = (float) i *dx;
		  Node *node = (Node*) it->next();
		  i++;
			if(x<lastx+textheight) continue;
			lastx = x;
		  setFont(getCurrentFont(), getCurrentFontSize(), "bold");
		  string prop = graph->getAsString(node, labelProp);
		  renderText(xpixels(-5.0),  1.0 - (float)(i)*dx, (char*) prop.c_str(), "right");
			int textx, texty, textw, texth;
			getBoundsText(textx,texty,textw,texth, prop.c_str(), getCurrentFont().c_str(), getCurrentFontSize());
			textheight = ypixels(texth);
		  setFont(getCurrentFont(), getCurrentFontSize(), "normal");
	  }
	  graph->destroyIterator(it);
	  

		// Border
		glLineWidth(1);
		glColor4f(0,0,0,0.7);
		glBegin(GL_LINE_LOOP);
		{
			glVertex2f(0,0);
			glVertex2f(1,0);
			glVertex2f(1,1);
			glVertex2f(0,1);
		}
		glEnd();
    glPointSize(1);
  }

  void mouseMove(float px, float py, float dx, float dy, int modifiers) { 
	  View::mouseMove(px, py, dx, dy, modifiers);
	  toView(px, py, mousex, mousey);
  }
	
	void update(string property) {
		if(property=="size") {
			invalidateGeometry = true;
		}
		if(property=="color" || property=="opacity") {
			invalidateColors = true;
		}
	}		
	void colorUpdated() {
    invalidateColors = true;
	}
};


View *createMatrixView(string name) {
	MatrixView *plot = new MatrixView(name.c_str());
	plot->setLocation(0.0, 1.0);
	plot->setSize(1.0, 0.7);
	plot->setVisible(true);
	plot->addSelectionWidget();
	plot->addCloseButton();
	plot->addTransparentButton();
	return plot;
}
